"""
ref: https://www.bilibili.com/video/BV1mp4y1V7ap/
"""


import win32gui
import win32con
import win32api


def get_hwnd():
    def find_window_handle(window_title):
        # 回调函数，用于EnumWindows时处理每个窗口
        def callback(hwnd, extra):
            window_text = win32gui.GetWindowText(hwnd)
            if window_text and window_title in window_text:
                extra.append(hwnd)
            return True

        handles = []
        win32gui.EnumWindows(callback, handles)
        return handles

    window_title_to_find = "原神"
    handles = find_window_handle(window_title_to_find)

    hwnd = 0
    for _hwnd in handles:
        class_name = win32gui.GetClassName(_hwnd)
        if class_name == 'UnityWndClass':
            hwnd = _hwnd
            break
    assert hwnd, 'hwnd为空?'
    return hwnd

    # win32gui.SetWindowPos(hwnd, win32con.HWND_TOP, 0, 0, 0, 0, win32con.SWP_SHOWWINDOW | win32con.SWP_NOSIZE)


import keyboard
from bdtime import tt
import mouse
import pydirectinput


def release_skill():
    hwnd = get_hwnd()
    window_rect, client_rect, title_bar_width, title_bar_height = get_title_bar_size(hwnd)
    x = (window_rect[0] + window_rect[2]) // 2
    y0 = (window_rect[1] + title_bar_height // 2)
    y1 = (window_rect[1] + window_rect[3]) // 2

    positions = [
        [x, y0],
        [x, y1]
    ]

    tt.sleep(0.5)

    keyboard.press('e')
    tt.sleep(0.25)
    keyboard.press('alt')

    tt.sleep(0.25)
    mouse.move(*positions[0])
    mouse.press(mouse.RIGHT)

    tt.sleep(0.1)
    keyboard.release('alt')
    keyboard.release('e')

    tt.sleep(2)

    mouse.move(*positions[1])
    mouse.release(mouse.RIGHT)


def get_title_bar_size(hwnd):
    window_rect = win32gui.GetWindowRect(hwnd)
    client_rect = win32gui.GetClientRect(hwnd)
    title_bar_width = (window_rect[2] - window_rect[0]) - (client_rect[2] - client_rect[0])
    title_bar_height = (window_rect[3] - window_rect[1]) - (client_rect[3] - client_rect[1])
    return window_rect, client_rect, title_bar_width, title_bar_height


if __name__ == '__main__':
    # mouse.move(x, y0)

    # move_window_to_lefp_up()
    print('~~~ start')
    keyboard.add_hotkey('alt + w', release_skill)
    keyboard.wait('alt + g')
